﻿/*****************************
 * Author: YanNI
 * Create：2017/7/6 9:08:06
 * Email:  admin@ircove.com
 * QQ:     401608886
 * TEl: 13520446271
 ****************************/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace VF.Ip
{
    /// <summary>
    /// ip数根
    /// </summary>
    internal class Root : Node
    {
        public Root(byte b) : base(b)
        {
        }
        public Node Add(byte[] bytes)
        {
            Node node = this.child[bytes[0]];

            for (int i = 1; i < 4; i++)
            {
                node = node.AddChild(bytes[i]);
            }

            return node;
        }

        public Address Search(byte[] bytes)
        {
            Node node = this.child[bytes[0]];
            int i = 1;
            while (i <= 3)
            {
                var tuple = node.findsim(bytes[i]);
                if (tuple.Item1)
                {
                    node = tuple.Item2;
                    i++;
                    continue;
                }
                else
                {
                    node = tuple.Item2;
                    while (i++ <= 3)
                    {
                        if (node.pos != -1)
                        {
                            return Address.GetAddress(node.pos);
                        }
                        node = node.child[0];
                    }
                    break;
                }
            }
            if (node.pos != -1)
            {
                return Address.GetAddress(node.pos);
            }
            return Address.GetAddress(0);
        }

    }
}
